<?php

namespace app\api\model;

use app\api\model\Goods\Speci\Color;
use app\api\model\Goods\Speci\Size;
use app\api\model\Goods\Speci\Style;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\Model;

class Product extends Model
{
    protected $table = 'jxc_product';
    protected $type = ['images' => 'json'];
    protected $autoWriteTimestamp = true;
    protected $updateTime = false;
    /**
     * @param int $page
     * @param int $size
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function paginatePassPage(int $page = 1, int $size = 10)
    {
        return $this->page($page, $size)->paginate($size);
    }

    public function getSizeAttr($value)
    {
        //return Size::field('id,name as size_name')->find($value);
        return Size::find($value)['name'];
    }

    public function getStyleAttr($value)
    {
        //return Style::field('id,name as style_name')->find($value);
        return Style::find($value)['name'];
    }

    public function getColorAttr($value)
    {
        //return Color::field('id,name as color_name')->find($value);
        return Color::find($value)['name'];
    }

    /**
     * @return \think\model\relation\BelongsTo
     */
    public function commodity()
    {
        return $this->belongsTo(Commodity::class, 'commodity_id');
    }

    /**
     * @return \think\model\relation\HasOne
     */
    public function stock()
    {
        return $this->hasOne(ProductStock::class, 'product_id');
    }

    public function purchaseRelation()
    {
        return $this->hasMany(PurchaseRelation::class, 'goods_id');
    }

    public function purchaseReturnRelation()
    {
        return $this->belongsTo(PurchaseReturn::class, 'goods_id');
    }

    public function prepareRelation()
    {
        return $this->hasMany(PrepareRelation::class, 'goods_id');
    }

    public function preparerReturnRelation()
    {
        return $this->hasMany(PrepareReturnRelation::class, 'goods_id');
    }

    public function productionRelation()
    {
        return $this->hasMany(ProductionRelation::class, 'goods_id');
    }

    public function allotRelation()
    {
        return $this->hasMany(AllotRelation::class, 'goods_id');
    }

    public function saleRelation()
    {
        return $this->hasMany(SaleRelation::class, 'goods_id');
    }

    public function saleReturnRelation()
    {
        return $this->hasMany(SaleReturnRelation::class, 'goods_id');
    }

    public function shop()
    {
        return $this->hasOne(ShopModel::class, 'product_id');
    }

    /**
     * @param $data
     * @param int $page
     * @param int $size
     * @return string|\think\Paginator
     */
    public function index($data, $page = 1, $size = 10)
    {
        try {
            return self::with('commodity')->where($data)->order('id')->page($page, $size)->paginate($size);
        } catch (DbException $e) {
            return $e->getMessage();
        }
    }

    /**
     * @param $id
     * @return array|\PDOStatement|string|Model|null
     */
    public function info($id)
    {
        try {
            return self::with('commodity')->findOrFail($id);
        } catch (DataNotFoundException $e) {
            return $e->getMessage();
        } catch (ModelNotFoundException $e) {
            return $e->getMessage();
        } catch (DbException $e) {
            return $e->getMessage();
        }
    }

    /**
     * @param array $data
     * @return Product
     */
    public function add(array $data)
    {
        $data['create_time'] = time();
        return self::create($data);
    }

    /**
     * @param array $data
     * @return \think\Collection
     * @throws \Exception
     */
    public function addAll(array $data)
    {
        $commodity = $data['commodity_id'];
        unset($data['commodity_id']);
        $f = [];
        foreach ($data as $k => $p) {
            $f[$k] = $p;
            $f[$k]['commodity_id'] = $commodity;
            $f[$k]['color'] = Color::where('name', $p['color'])->find()['id'];
            $f[$k]['size'] = Size::where('name', $p['size'])->find()['id'];
            $f[$k]['style'] = Style::where('name', $p['style'])->find()['id'];
        }
        return  $this->saveAll($f);
    }

    /**
     * @param array $data
     * @return array
     */
    public function batchAdd(array $data)
    {
        $spe = [];
        $arr = [];
        $group = array_filter($data, function ($v, $k) {
            return in_array($k, ['color', 'style', 'size'], true);
        }, ARRAY_FILTER_USE_BOTH);
        if (!empty(array_keys($group, 'style', true))) {
            // 处理 多个规格的混合组合
            foreach ($data['color'] as $key => $val) {
                foreach ($data['size'] as $key1 => $val1) {
                    foreach ($data['style'] as $key2 => $val2) {
                        $spe[] = [
                            'color' => $data['color'][$key],
                            'size' => $data['size'][$key1],
                            'style' => $data['style'][$key2]
                        ];
                    }
                }
            }
            foreach ($spe as $k => $v) {
                $data['color'] = $v['color'];
                $data['size'] = $v['size'];
                $data['style'] = $v['style'];
                $res = $this->add($data);
                $arr[] = $res->id;
                $res->stock()->save(['stock' => $data['stock'], 'commodity_id' => $data['commodity_id']]);
            }
            // 不传款式，则只处理颜色和尺寸
        } else {
            foreach ($data['color'] as $key => $val) {
                foreach ($data['size'] as $key1 => $val1) {
                    $spe[] = ['color' => $data['color'][$key], 'size' => $data['size'][$key1],];
                }
            }
            foreach ($spe as $k => $v) {
                $data['color'] = $v['color'];
                $data['size'] = $v['size'];
                $res = $this->add($data);
                $arr[] = $res->id;
                $res->stock()->save(['stock' => $data['stock'], 'commodity_id' => $data['commodity_id']]);
            }
        }
        return $arr;
    }

    /**
     * @param int $id
     * @param array $data
     * @return int|string
     */
    public function edit(int $id, array $data)
    {
        try {
            return self::where(['id' => $id])->update($data);
        } catch (PDOException $e) {
            return $e->getMessage();
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }

    /**
     * @param int $id
     * @return int
     */
    public function del(int $id)
    {
        try {
            return self::where('id', $id)->delete();
        } catch (PDOException $e) {
            return $e->getMessage();
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }


    public function getAllProduct($id)
    {
        $list =self::field('id,color,size')->where('commodity_id',$id)->select();
        return $list;
    }
}
